<?php

namespace app\common\model\subscribe;

use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use Throwable;
use function config;

class SubscribeRecord extends Model
{

    // 默认表名
    protected $name = 'subscribe_record';

    const TABLE_NUM = 10;

    /**
     * 如果表不存在，则创建新表
     *
     * @param $tableName
     * @return bool
     * @throws Throwable 如果创建表失败，抛出异常
     */
    public static function createTableIfNotExists($tableName): bool
    {
        $cacheKey = 'makeTable:' . $tableName;
        $check = Cache::get($cacheKey);
        if ($check) {
            return true;
        }
        // 检查表是否存在
        $exists = Db::query("SHOW TABLES LIKE  '{$tableName}'");

        if (!$exists) {
            $sql = <<<SQL
            CREATE TABLE `{$tableName}`  (
              `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
              `user_id` int(11) DEFAULT NULL,
              `subscribe_user_id` int(11) DEFAULT NULL,
              `amount` decimal(10,2) DEFAULT NULL COMMENT '订阅价格',
              `create_time` int(11) DEFAULT NULL COMMENT '订阅时间',
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订阅记录';
        SQL;

            try {
                Db::execute($sql);
            } catch (Throwable $e) {
                // 记录异常信息
                Log::channel('my')->error("Failed to create table {$tableName}: " . $e->getMessage());
                // 可以选择抛出异常或返回错误信息
                throw new \RuntimeException("Failed to create table: " . $e->getMessage(), 0, $e);
            }
        }

        //创建表
        Cache::set($cacheKey, 1);
        return true;
    }

    /**
     * 实例化表
     * @param $userId
     * @return SubscribeRecord
     * @throws Throwable
     */
    public static function initModel($userId): static
    {
        $model = new static();
        $tableName = $model->name . '_' . ($userId % self::TABLE_NUM);
        $model->setName($tableName);

        $prefix = config('database.connections.mysql.prefix');
        //创建表
        self::createTableIfNotExists($prefix . $tableName);

        return $model;
    }
}